//
//  CXTabBar.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/18.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

class CXTabBar: UITabBar {
    
    var composedClick:(()->Void)?
    
    //重写初始化方法 在创建的时候生成中间的按钮 无论哪个初始化方法 都会调用到该方法
    //只适用于纯代码创建。如果是从xib或者sb中创建,则不会调用该方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composedBtn)
        backgroundImage = UIImage(named: "tabbar_background")
    }
    /// 重写该方法,在其中加入与init(frame:)一样的内容，代表self是从xib或者sb中创建
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //在layoutSubview中进行布局. 该方法在viewWillLayout的时候开始调用
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composedBtn.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5)
        //子控件的宽度
        let itemWidth = frame.width * 0.2
        var index:CGFloat = 0.0
        for subItem in subviews {
            
            if subItem.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                if index == 2 {
                    index++
                }
                subItem.frame.origin.x = index * itemWidth
                index++
            }
        }
    }
    //MARK:composed按钮的点击事件.使用oc运行时的事件触发来处理该事件
    @objc private func composedBtnClick() {
        composedClick?()
    }
    //MARK: 中间按钮的懒加载getter
    private lazy var composedBtn:UIButton = {
        
        let button = UIButton()
        button.addTarget(self, action: "composedBtnClick", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.sizeToFit()
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        return button
    }()

}
